package br.com.dev.tcc.task;

import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import br.com.dev.tcc.R;
import br.com.dev.tcc.bean.DelegateListener;
import br.com.dev.tcc.bean.ResponseData;

import com.google.android.gms.maps.model.LatLng;

public class BuscaLocaisProximosTask extends AsyncTask<Void, Void, ResponseData<String>> {

	private Context context;
	private LatLng latLng;
	private DelegateListener<ResponseData<String>> delegate;

	public BuscaLocaisProximosTask(Context  context, LatLng latLng, DelegateListener<ResponseData<String>> delegate){
		this.context = context;
		this.latLng = latLng;
		this.delegate = delegate;
	}
	
	@Override
	protected ResponseData<String> doInBackground(Void... params) {

		boolean success = false;
		String endereco = null;
		String erro = null;
		
		try{
			Geocoder geocoder;
			geocoder = new Geocoder(context, Locale.getDefault());
			List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
			Address address = addresses.get(0);
			endereco = address.getAddressLine(0).concat(", ").concat(address.getAddressLine(1));
			success = true;
		}
		catch(Exception e){
			erro = context.getString(R.string.erro_obter_endereco);
		}
		
		return new ResponseData<String>(success, erro, endereco);
	}
	
	@Override
	protected void onPostExecute(ResponseData<String> result) {

		delegate.onDelegate(result);
	}
}
